package cn.iocoder.yudao.module.signature.service.developeraccount;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.text.CharSequenceUtil;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.framework.mybatis.core.query.LambdaQueryWrapperX;
import cn.iocoder.yudao.framework.security.core.LoginUser;
import cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils;
import cn.iocoder.yudao.module.infra.api.file.FileApi;
import cn.iocoder.yudao.module.member.api.config.UserPoolConfigApi;
import cn.iocoder.yudao.module.member.api.config.dto.UserPoolConfigRespDTO;
import cn.iocoder.yudao.module.member.api.point.MemberPointApi;
import cn.iocoder.yudao.module.member.enums.point.MemberPointBizTypeEnum;
import cn.iocoder.yudao.module.signature.appconnect.model.*;
import cn.iocoder.yudao.module.signature.appconnect.util.AppleConnectUtil;
import cn.iocoder.yudao.module.signature.appconnect.util.TokenUtil;
import cn.iocoder.yudao.module.signature.controller.admin.developeraccount.vo.DeveloperAccountPageReqVO;
import cn.iocoder.yudao.module.signature.controller.admin.developeraccount.vo.DeveloperAccountRespVO;
import cn.iocoder.yudao.module.signature.controller.admin.developeraccount.vo.DeveloperAccountSaveReqVO;
import cn.iocoder.yudao.module.signature.controller.admin.developeraccountversion.vo.DeveloperAccountVersionRespVO;
import cn.iocoder.yudao.module.signature.controller.admin.developeraccountversion.vo.DeveloperAccountVersionSaveReqVO;
import cn.iocoder.yudao.module.signature.controller.admin.device.vo.AppleDeviceSaveReqVO;
import cn.iocoder.yudao.module.signature.controller.app.developeraccount.vo.SyncDeviceReqVO;
import cn.iocoder.yudao.module.signature.dal.dataobject.developeraccount.DeveloperAccountDO;
import cn.iocoder.yudao.module.signature.dal.dataobject.device.AppleDeviceDO;
import cn.iocoder.yudao.module.signature.dal.mysql.developeraccount.DeveloperAccountMapper;
import cn.iocoder.yudao.module.signature.enums.AppleAccountType;
import cn.iocoder.yudao.module.signature.enums.EnableType;
import cn.iocoder.yudao.module.signature.model.CertificateCreateModel;
import cn.iocoder.yudao.module.signature.model.GetAvailableAccountModel;
import cn.iocoder.yudao.module.signature.service.developeraccountversion.DeveloperAccountVersionService;
import cn.iocoder.yudao.module.signature.service.device.AppleDeviceService;
import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;
import java.io.File;
import java.io.FileOutputStream;
import java.nio.file.Files;
import java.security.KeyFactory;
import java.security.KeyStore;
import java.security.PrivateKey;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.security.spec.PKCS8EncodedKeySpec;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.signature.appconnect.util.AppleConnectUtil.DEFAULT_CRT_PASSWORD;
import static cn.iocoder.yudao.module.signature.appconnect.util.AppleConnectUtil.PRIVATE_KEY_CONTENT;
import static cn.iocoder.yudao.module.signature.enums.ErrorCodeConstants.DEVELOPER_ACCOUNT_NOT_EXISTS;

/**
 * 苹果开发者账号 Service 实现类
 *
 * @author base
 */
@Service
@Validated
@Slf4j
public class DeveloperAccountServiceImpl implements DeveloperAccountService {

    @Resource
    private DeveloperAccountMapper developerAccountMapper;

    @Resource
    @Lazy
    private AppleDeviceService deviceService;

    @Resource
    @Lazy
    private DeveloperAccountService accountService;

    @Resource
    private UserPoolConfigApi userPoolConfigApi;

    @Resource
    private DeveloperAccountVersionService accountVersionService;

    @Resource
    private FileApi fileApi;

    @Resource
    private MemberPointApi memberPointApi;



    /**
     * 设备数量上限
     */
    private static final Integer TOTAL_DEVICE_SIZE = 100;

    /**
     * App Store Connect 的 Issuer ID
     */
    private static final String ISSUER_ID = "09878b45-577b-49c6-98dd-276c43c53ffb";

    /**
     * App Store Connect 的 Key ID
     */
    private static final String KEY_ID = "GQBSAL5XD8";

    /**
     * App Store Connect 的 Private Key 的路径
     */
    private static final String PRIVATE_KEY_PATH = "C:\\Users\\liujq\\Downloads\\1a19cd03886cecb3c446c316ce1fd2a2cdc6da1c65db746ca5c603fb1596dbca.p8";

    /**
     * 支持的能力类型
     */
    private static final List<String> CAPABILITY_TYPE = Lists.newArrayList("ICLOUD", "IN_APP_PURCHASE","GAME_CENTER","PUSH_NOTIFICATIONS","WALLET","INTER_APP_AUDIO",
            "MAPS","ASSOCIATED_DOMAINS","PERSONAL_VPN","APP_GROUPS","HEALTHKIT","HOMEKIT","WIRELESS_ACCESSORY_CONFIGURATION","APPLE_PAY","DATA_PROTECTION","SIRIKIT","NETWORK_EXTENSIONS",
            "MULTIPATH","HOT_SPOT","NFC_TAG_READING","CLASSKIT","AUTOFILL_CREDENTIAL_PROVIDER","ACCESS_WIFI_INFORMATION","NETWORK_CUSTOM_PROTOCOL","COREMEDIA_HLS_LOW_LATENCY",
            "SYSTEM_EXTENSION_INSTALL","USER_MANAGEMENT","APPLE_ID_AUTH");


    public static void main(String[] args) throws Exception {
        String token = TokenUtil.generateToken(ISSUER_ID, KEY_ID, FileUtil.readBytes(PRIVATE_KEY_PATH));


        Map<String, List<String>> deviceList = AppleConnectUtil.getDeviceList(token, Lists.newArrayList());
        log.info("deviceList:{}", deviceList);
        CertificateResponse defaultCertificate = AppleConnectUtil.createDefaultCertificate(token);
        String certificateContent = defaultCertificate.getData().getAttributes().getCertificateContent();

        File tempFile = FileUtil.createTempFile(".cer", false);
        FileUtil.writeBytes(Base64.getDecoder().decode(certificateContent), tempFile);

        String fileName = UUID.fastUUID() + "." + FileUtil.getSuffix(tempFile);

        //crt文件路径
        log.info("crtFilePath:{}", fileName);

        //创建p12证书
        //加载证书
        X509Certificate certificate = (X509Certificate) CertificateFactory.getInstance("X.509").generateCertificate(Files.newInputStream(tempFile.toPath()));
        log.info("加载证书成功");

        //加载私钥
        byte[] decodedKey = Base64.getDecoder().decode(PRIVATE_KEY_CONTENT);
        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(decodedKey);
        PrivateKey privateKey = KeyFactory.getInstance("RSA").generatePrivate(keySpec);
        log.info("加载私钥成功");

        // 创建 KeyStore
        KeyStore keyStore = KeyStore.getInstance("PKCS12");
        keyStore.load(null, null);
        keyStore.setKeyEntry("1", privateKey, DEFAULT_CRT_PASSWORD.toCharArray(), new java.security.cert.Certificate[]{certificate});

        File p12File = FileUtil.createTempFile(".p12", false);

        // 保存为 .p12 文件
        try (FileOutputStream fos = new FileOutputStream(p12File)) {
            keyStore.store(fos, DEFAULT_CRT_PASSWORD.toCharArray());
        }
        log.info("p12文件创建成功");

        String p12FileName = UUID.fastUUID() + "." + FileUtil.getSuffix(p12File);

        log.info("p12FilePath:{}", p12FileName);

        log.info("defaultCertificate:{}", defaultCertificate);

//        System.out.println(token);
    }


    /**
     * 新建开发者账号
     *
     * @param createReqVO 创建信息
     * @return 创建一个
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Long createDeveloperAccount(DeveloperAccountSaveReqVO createReqVO) throws Exception {

        List<UserPoolConfigRespDTO> config = userPoolConfigApi.getConfig();



        //获取token
        String token = TokenUtil.generateToken(createReqVO.getIssId(), createReqVO.getKId(), createReqVO.getP8Url(), fileApi);
        log.info("get app connect token:{}", token);

        //获取证书列表
        List<Certificate> certificates = AppleConnectUtil.getCertificates(token);
        Assert.isTrue(certificates.stream()
                        .filter(certificate -> certificate.getAttributes().getCertificateType().equals(CertificateType.IOS_DISTRIBUTION)).count() < 3,
                "证书数量已达上限");


        //获取设备列表
        Map<String, List<String>> deviceList = AppleConnectUtil.getDeviceList(token, Lists.newArrayList());

        //获取用户信息
        User userInfo = AppleConnectUtil.getUserInfo(token);

        //创建一个包名
        String bundleId = AppleConnectUtil.createDefaultBundleId(token);

        //创建一个证书 保存证书内容
        CertificateCreateModel defaultCertificateModel = AppleConnectUtil.createDefaultCertificateModel(token, fileApi);
        log.info("defaultCertificateModel:{}", defaultCertificateModel);

        //创建开发者账号
        DeveloperAccountDO developerAccount = BeanUtils.toBean(createReqVO, DeveloperAccountDO.class);

        developerAccount.setMacRemaining(CollectionUtils.isEmpty(deviceList.get(DeviceClass.MAC.value())) ? TOTAL_DEVICE_SIZE : TOTAL_DEVICE_SIZE - deviceList.get(DeviceClass.MAC.value()).size());
        developerAccount.setIphoneRemaining(CollectionUtils.isEmpty(deviceList.get(DeviceClass.IPHONE.value())) ? TOTAL_DEVICE_SIZE : TOTAL_DEVICE_SIZE - deviceList.get(DeviceClass.IPHONE.value()).size());
        developerAccount.setIpadRemaining(CollectionUtils.isEmpty(deviceList.get(DeviceClass.IPAD.value())) ? TOTAL_DEVICE_SIZE : TOTAL_DEVICE_SIZE - deviceList.get(DeviceClass.IPAD.value()).size());

        developerAccount.setBId(bundleId);
        developerAccount.setCerName(defaultCertificateModel.getName());
        developerAccount.setCerNumber(defaultCertificateModel.getSerialNumber());
        developerAccount.setCId(defaultCertificateModel.getCrtId());
        developerAccount.setExpireDate(defaultCertificateModel.getExpireDate());
        developerAccount.setP12Url(defaultCertificateModel.getP12Path());
        developerAccount.setP12Password(defaultCertificateModel.getPassword());
        developerAccount.setDeveloperAccount(userInfo.getAttributes().getUsername());
        developerAccount.setDeveloperName(userInfo.getAttributes().getFirstName() + userInfo.getAttributes().getLastName());
        if (developerAccount.getAccountBelongType().equals(String.valueOf(AppleAccountType.PUBLIC_POOL.getType()))) {
            developerAccount.setIpadCount(0);
            developerAccount.setIphoneCount(0);
            developerAccount.setMacCount(0);
        }
        // 插入
        developerAccountMapper.insert(developerAccount);
        if (!CollectionUtil.isEmpty(config)) {
            List<DeveloperAccountVersionSaveReqVO> accountVersionSaveReqVOS = config.stream().map(userPoolConfigRespDTO -> {
                DeveloperAccountVersionSaveReqVO reqVO = new DeveloperAccountVersionSaveReqVO();
                reqVO.setAccountId(developerAccount.getId());
                reqVO.setVersionTypeCode(userPoolConfigRespDTO.getVersionTypeCode());
                reqVO.setEnableFlag(EnableType.ENABLE.getType());
                return reqVO;

            }).collect(Collectors.toList());
            accountVersionService.createBatch(accountVersionSaveReqVOS);
        }

        if(StringUtils.equals(String.valueOf(AppleAccountType.INDEPENDENT_POOL.getType()) ,createReqVO.getAccountBelongType())){
            memberPointApi.updateRecordByType(createReqVO.getUserId(),null, MemberPointBizTypeEnum.REDUCE_UP_P8_SPENDING_POWER.getType());
        }

        fileApi.moveFile(CharSequenceUtil.subAfter( createReqVO.getP8Url(), "/get/", false),"p8");

        // 返回
        return developerAccount.getId();
    }

    @Transactional(rollbackFor = Exception.class,propagation = Propagation.REQUIRES_NEW)
    @Override
    public void refreshRemaining(Long id, Long userId) throws Exception {
        log.info("刷新余量开始,id:{},userId:{}", id, userId);
        DeveloperAccountDO developerAccountDO = developerAccountMapper.selectOne(new LambdaQueryWrapperX<DeveloperAccountDO>()
                .eq(DeveloperAccountDO::getId, id)
                .eqIfPresent(DeveloperAccountDO::getUserId, userId));
        Assert.notNull(developerAccountDO, "开发者账号不存在");


        String path = CharSequenceUtil.subAfter(developerAccountDO.getP8Url(), "/get/", false);
        String configId = developerAccountDO.getP8Url().substring(developerAccountDO.getP8Url().indexOf("/file/") + "/file/".length(), developerAccountDO.getP8Url().indexOf("/get/"));

        byte[] fileContent = fileApi.getFileContent(Long.valueOf(configId), path);
        String token = TokenUtil.generateToken(developerAccountDO.getIssId(), developerAccountDO.getKId(), fileContent);


        Map<String, List<Device>> iosDeviceList = AppleConnectUtil.getDevices(token, Lists.newArrayList(BundleIdPlatform.IOS.value()));

        developerAccountDO.setIphoneRemaining(CollectionUtils.isEmpty(iosDeviceList.get(DeviceClass.IPHONE.value())) ? TOTAL_DEVICE_SIZE : TOTAL_DEVICE_SIZE - iosDeviceList.get(DeviceClass.IPHONE.value()).size());
        developerAccountDO.setIpadRemaining(CollectionUtils.isEmpty(iosDeviceList.get(DeviceClass.IPAD.value())) ? TOTAL_DEVICE_SIZE : TOTAL_DEVICE_SIZE - iosDeviceList.get(DeviceClass.IPAD.value()).size());

        Map<String, List<Device>> macDeviceList = AppleConnectUtil.getDevices(token, Lists.newArrayList(BundleIdPlatform.MAC_OS.value()));
        developerAccountDO.setMacRemaining(CollectionUtils.isEmpty(macDeviceList.get(DeviceClass.MAC.value())) ? TOTAL_DEVICE_SIZE : TOTAL_DEVICE_SIZE - macDeviceList.get(DeviceClass.MAC.value()).size());

        // 如果是优先账号 并且iphone余量和mac余量都到90了 则禁用账号
        if (developerAccountDO.getAccountBelongType().equals(String.valueOf(AppleAccountType.PUBLIC_POOL.getType())) &&
                developerAccountDO.getIphoneRemaining() <= 90 && developerAccountDO.getMacRemaining() <= 90
            && Objects.equals(developerAccountDO.getPreferFlag(),1)) {
            log.info("iphone余量和mac余量都到90了,禁用账号{}", developerAccountDO.getDeveloperName());
            developerAccountDO.setEnableFlag(EnableType.DISABLE.getType());
            accountService.updateByIdNow(developerAccountDO);
        }

        developerAccountMapper.updateById(developerAccountDO);

    }


    @Override
    public void updateDeveloperAccount(DeveloperAccountSaveReqVO updateReqVO) {
        // 校验存在
        validateDeveloperAccountExists(updateReqVO.getId(), updateReqVO.getUserId());
        // 更新
        DeveloperAccountDO updateObj = BeanUtils.toBean(updateReqVO, DeveloperAccountDO.class);

        //更新版本信息
        DeveloperAccountVersionSaveReqVO accountVersionSaveReqVO = updateReqVO.getAccountVersionSaveReqVO();
        if (null != accountVersionSaveReqVO) {
            accountVersionService.updateByAccountIdAndTypeCode(
                    accountVersionSaveReqVO.getAccountId(),
                    accountVersionSaveReqVO.getVersionTypeCode(),
                    accountVersionSaveReqVO.getEnableFlag());
        }
        developerAccountMapper.updateById(updateObj);
        fileApi.moveFile(CharSequenceUtil.subAfter( updateReqVO.getP8Url(), "/get/", false),"p8");
    }

    @Override
    public void deleteDeveloperAccount(List<Long> ids, Long userId) {
        // 校验存在
        validateDeveloperAccountExists(ids, userId);
        // 删除
        developerAccountMapper.deleteByIds(ids);
    }

    private void validateDeveloperAccountExists(List<Long> ids, Long userId) {
        if (developerAccountMapper.selectCount(new LambdaQueryWrapperX<DeveloperAccountDO>()
                .in(DeveloperAccountDO::getId, ids)
                .eqIfPresent(DeveloperAccountDO::getUserId, userId)) != ids.size()) {
            throw exception(DEVELOPER_ACCOUNT_NOT_EXISTS);
        }
    }
    private void validateDeveloperAccountExists(Long id, Long userId) {
        if (developerAccountMapper.selectOne(new LambdaQueryWrapperX<DeveloperAccountDO>()
                .eq(DeveloperAccountDO::getId, id)
                .eqIfPresent(DeveloperAccountDO::getUserId, userId)) == null) {
            throw exception(DEVELOPER_ACCOUNT_NOT_EXISTS);
        }
    }
    @Override
    public DeveloperAccountRespVO getDeveloperAccount(Long id, Long userId) {
        DeveloperAccountDO developerAccountDO = developerAccountMapper.selectOne(new LambdaQueryWrapperX<DeveloperAccountDO>()
                .eq(DeveloperAccountDO::getId, id)
                .eqIfPresent(DeveloperAccountDO::getUserId, userId));
        Assert.notNull(developerAccountDO, "开发者账号不存在");

        DeveloperAccountRespVO developerAccountRespVO = BeanUtils.toBean(developerAccountDO, DeveloperAccountRespVO.class);

        Map<Long, List<DeveloperAccountVersionRespVO>> accountVersionMap = accountVersionService.getByAccounts(Lists.newArrayList(developerAccountDO.getId()));
        if (accountVersionMap.get(developerAccountDO.getId()) != null) {
            developerAccountRespVO.setAccountVersionRespVOS(accountVersionMap.get(developerAccountDO.getId()));
        }

        return developerAccountRespVO;

    }

    @Override
    public PageResult<DeveloperAccountRespVO> getDeveloperAccountPage(DeveloperAccountPageReqVO pageReqVO) {
        PageResult<DeveloperAccountDO> developerAccountDOPageResult = developerAccountMapper.selectPage(pageReqVO);
        PageResult<DeveloperAccountRespVO> respVOPageResult = BeanUtils.toBean(developerAccountDOPageResult, DeveloperAccountRespVO.class);
        if (CollUtil.isNotEmpty(respVOPageResult.getList())) {
            Map<Long, List<DeveloperAccountVersionRespVO>> accountVersionMap = accountVersionService.getByAccounts(respVOPageResult.getList().stream().map(DeveloperAccountRespVO::getId).collect(Collectors.toList()));
            respVOPageResult.getList().forEach(developerAccountRespVO -> {
                developerAccountRespVO.setAccountVersionRespVOS(accountVersionMap.get(developerAccountRespVO.getId()));
            });
        }
        return respVOPageResult;
    }

    @Override
    public DeveloperAccountDO getAvailableDeveloperAccount(GetAvailableAccountModel model) {
        return developerAccountMapper.getAvailableDeveloperAccount(model);
    }

    @Override
    public String downloadMobileProvision(Long id, Long userId) throws Exception {
        DeveloperAccountDO accountDO = developerAccountMapper.selectOne(new LambdaQueryWrapperX<DeveloperAccountDO>()
                .eq(DeveloperAccountDO::getId, id)
                .eqIfPresent(DeveloperAccountDO::getUserId, userId));

        //获取token
        String token = TokenUtil.generateToken(accountDO.getIssId(), accountDO.getKId(), accountDO.getP8Url(), fileApi);

        //获取所有设备
        List<String> deviceIds = AppleConnectUtil.getDeviceList(token, Lists.newArrayList()).values().stream().flatMap(Collection::stream).collect(Collectors.toList());
        log.info("获取到的设备列表为:{}", JSON.toJSONString(deviceIds));
        Assert.notEmpty(deviceIds, "当前账号暂未维护设备信息");

        //创建描述文件
        return AppleConnectUtil.createProfileAndSave(token,accountDO.getBId(), accountDO.getCId(), deviceIds, fileApi);

    }

    @Override
    public boolean refreshProfile(Long id) throws Exception {
        DeveloperAccountDO accountDO = developerAccountMapper.selectById(id);
        Assert.notNull(accountDO, "开发者账号不存在");
        String token = TokenUtil.generateToken(accountDO.getIssId(), accountDO.getKId(), accountDO.getP8Url(), fileApi);
        log.info("token:{}", token);

        // 计数
        AtomicInteger count = new AtomicInteger(0);
        CAPABILITY_TYPE.parallelStream().forEach(s -> {
            boolean syncSuccess ;
            try {
                syncSuccess = AppleConnectUtil.refreshProfile(token, accountDO.getBId(), s);
            } catch (Exception e) {
                log.error("刷新描述文件失败,错误信息:{}", e.getMessage());
                syncSuccess = false;
            }
            if (syncSuccess) {
                count.getAndIncrement();
            }
        });
        accountDO.setWeight(count.get());
        developerAccountMapper.updateById(accountDO);
        return true;
    }

    /**
     * 同步设备 只同步 ipone和ipad
     *
     * @param reqVO
     * @throws Exception
     */
    @Override
    public void syncDevice(SyncDeviceReqVO reqVO) throws Exception {
        LoginUser loginUser = SecurityFrameworkUtils.getLoginUser();
        Assert.notNull(loginUser, "用户未登录");

        DeveloperAccountDO accountDO = developerAccountMapper.selectOne(new LambdaQueryWrapperX<DeveloperAccountDO>()
                .eq(DeveloperAccountDO::getId, reqVO.getAccountId())
                .eqIfPresent(DeveloperAccountDO::getUserId, loginUser.getId()));
        Assert.notNull(accountDO, "开发者账号不存在");

        String token = TokenUtil.generateToken(accountDO.getIssId(), accountDO.getKId(), accountDO.getP8Url(), fileApi);

        //获取设备列表
        Map<String, List<Device>> deviceList = AppleConnectUtil.getDevices(token, Lists.newArrayList(reqVO.getPlatform()));

        List<AppleDeviceDO> deviceDOS = deviceService.getByUserId(loginUser.getId());

        deviceList.values().stream().flatMap(Collection::stream).forEach(device -> {
            AppleDeviceDO deviceDO = deviceDOS.stream().filter(appleDeviceDO -> appleDeviceDO.getUdid().equals(device.getAttributes().getUdid())).findFirst().orElse(null);
            if (null != deviceDO) {
                log.info("设备已存在,udid:{}", device.getAttributes().getUdid());
                return;
            }
            accountService.doSyncDevice(accountDO, device,token);
        });

    }

    @Override
    public void delete(List<Long> idList) {
        Assert.notEmpty(idList, "删除数据时，主键集合不能为空！");
        List<DeveloperAccountDO> developerAccountDOS = developerAccountMapper.selectBatchIds(idList);
        Assert.notEmpty(developerAccountDOS, "删除数据时，未查询到需要删除的数据！");
        developerAccountMapper.deleteByIds(developerAccountDOS.stream().map(DeveloperAccountDO::getId).collect(Collectors.toList()));
    }

    @Override
    public void enable(List<Long> idList) {
        Assert.notEmpty(idList, "启用数据时，主键集合不能为空！");
        List<DeveloperAccountDO> developerAccountDOS = developerAccountMapper.selectBatchIds(idList);

        developerAccountDOS.forEach(developerAccountDO -> developerAccountDO.setEnableFlag(EnableType.ENABLE.getType()));
        developerAccountMapper.updateBatch(developerAccountDOS);
    }

    @Override
    public void disable(List<Long> idList) {
        Assert.notEmpty(idList, "禁用数据时，主键集合不能为空！");
        List<DeveloperAccountDO> developerAccountDOS = developerAccountMapper.selectBatchIds(idList);
        developerAccountDOS.forEach(developerAccountDO -> developerAccountDO.setEnableFlag(EnableType.DISABLE.getType()));
        developerAccountMapper.updateBatch(developerAccountDOS);
    }

    @Override
    public DeveloperAccountDO getById(Long id) {
        return developerAccountMapper.selectById(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class,propagation = Propagation.REQUIRES_NEW)
    public void updateByIdNow(DeveloperAccountDO accountDO) {
        developerAccountMapper.updateById(accountDO);
    }


    @Override
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRES_NEW)
    public void doSyncDevice(DeveloperAccountDO accountDO, Device device,String token) {
        String mpUrl = AppleConnectUtil.createProfileAndSave(token, accountDO.getBId(), accountDO.getCId(), device.getId(), fileApi);
        if(null == mpUrl){
            log.error("创建描述文件失败,udid:{}",device.getAttributes().getUdid());
            return;
        }
        log.info("创建描述文件返回结果为:{}", mpUrl);

        AppleDeviceSaveReqVO deviceSaveReqVO = new AppleDeviceSaveReqVO();
        deviceSaveReqVO.setUdid(device.getAttributes().getUdid());
        deviceSaveReqVO.setDeviceModel(device.getAttributes().getModel());
        deviceSaveReqVO.setDeviceId(device.getId());
        deviceSaveReqVO.setCerId(accountDO.getCId());
        deviceSaveReqVO.setCerNumber(accountDO.getCerNumber());
        deviceSaveReqVO.setAppAccountId(accountDO.getId());
        deviceSaveReqVO.setAccountType(accountDO.getAccountBelongType());
        deviceSaveReqVO.setCerName(accountDO.getCerName());
        deviceSaveReqVO.setP12Url(accountDO.getP12Url());
        deviceSaveReqVO.setP12Password(accountDO.getP12Password());
        deviceSaveReqVO.setMpUrl(mpUrl);

        deviceSaveReqVO.setUserId(accountDO.getUserId());
        deviceService.createAppleDevice(deviceSaveReqVO);

    }

}
